<template>
  <div class="echarts-bar-container">
    <!-- 顶部 -->
    <div class="top-title">
      <!-- 左侧标题区域 -->
      <div class="title-area">
        <img :src="lefticon" class="icon" />
        <span class="chart-title">{{ chartTitle }}</span>
      </div>
      <!-- 右侧下拉区域 -->
      <div class="dropdown-area">
        <el-select
          v-model="selectedTimeRange"
          placeholder="请选择"
          @change="handleTimeRangeChange"
        >
          <el-option
            v-for="(item, index) in timeRangeOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <!-- ECharts 容器 -->
    <div ref="echartsDom" class="echarts-box" />
  </div>
</template>

<script setup>
  import { ref, onMounted, watch, nextTick } from 'vue'
  import * as echarts from 'echarts'
  import { ElSelect, ElOption } from 'element-plus'
  import 'element-plus/dist/index.css'
  import pieimage from '@/assets/logo.png'
  import lefticon from '@/assets/operation/lefticon.png'

  const props = defineProps({
    // 柱状图标题
    chartTitle: {
      type: String,
      default: '任务性质'
    },
    // 标题左侧小图标背景色（实际这里用图片，可忽略颜色逻辑，保留是为了兼容原结构）
    titleIconColor: {
      type: String,
      default: '#409eff'
    },
    // 下拉选项数据
    timeRangeOptions: {
      type: Array,
      default: () => [
        { label: '本日', value: 'today' },
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' }
      ]
    },
    // 不同时间范围的数据，改造为柱状图所需结构：
    // 每个数据集包含 xAxisData（小时）、seriesData（各类型数据数组）
    chartDatasets: {
      type: Array,
      default: () => [
        {
          // 本日数据示例
          xAxisData: ['0', '4', '8', '12', '16', '20', '24'],
          seriesData: [
            {
              name: '城管执法',
              type: 'bar',
              data: [30, 70, 60, 90, 35, 50, 80],
              color: '#3d7fff'
            },
            {
              name: '交通巡查',
              type: 'bar',
              data: [80, 55, 50, 60, 80, 40, 50],
              color: '#ff6961'
            },
            {
              name: '河湖巡查',
              type: 'bar',
              data: [55, 35, 85, 40, 60, 70, 20],
              color: '#f9c851'
            }
          ]
        }
      ]
    }
  })

  const emit = defineEmits(['data-change'])

  const echartsDom = ref(null)
  let myChart = null
  const selectedTimeRange = ref(props.timeRangeOptions[0].value)
  const currentChartData = ref(props.chartDatasets[0])

  onMounted(() => {
    initEcharts()
  })

  watch(
    () => props.chartDatasets,
    () => {
      initEcharts()
    }
  )
  const image = ref(pieimage)
  // 初始化 ECharts
  const initEcharts = () => {
    if (echartsDom.value) {
      myChart = echarts.init(echartsDom.value)
      const option = {
        grid: {
          left: '0%',
          right: '8%',
          bottom: '3%',
          top: '40', // 为图例留出空间
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          show: true,
          right: 10,
          top: 0,
          itemGap: 20,
          itemHeight: 8,
          itemWidth: 8,
          icon: 'rect',
          textStyle: {
            fontSize: 12 // 字体大小15px
          }
        },
        xAxis: {
          type: 'category',
          data: currentChartData.value.xAxisData,
          axisLabel: {
            fontSize: 12
          },
          name: '(h)',
          nameTextStyle: {
            fontSize: 12,
            padding: [0, 0, 0, 0]
          }
        },
        yAxis: {
          type: 'value',
          name: '(个)',
          nameTextStyle: {
            fontSize: 12,
            padding: [0, 40, 5, 5]
          },
          axisLabel: {
            fontSize: 12
          }
        },
        series: currentChartData.value.seriesData.map((series) => ({
          ...series,
          // 设置柱形宽度为9px
          barWidth: 9
        }))
      }
      myChart.setOption(option)
      // 监听容器大小变化，自适应图表
      window.addEventListener('resize', () => {
        if (myChart) {
          myChart.resize()
        }
      })
    }
  }

  // 处理时间范围切换
  const handleTimeRangeChange = (value) => {
    const targetDataset = props.chartDatasets.find(
      (item, index) => props.timeRangeOptions[index].value === value
    )
    if (targetDataset) {
      currentChartData.value = targetDataset
      if (myChart) {
        myChart.setOption({
          xAxis: {
            data: targetDataset.xAxisData
          },
          series: targetDataset.seriesData
        })
      }
      emit('data-change', targetDataset)
    }
  }

  // 使响应式数据更新后图表能正确重绘（结合 Vue3 响应式原理）
  watch(currentChartData, () => {
    nextTick(() => {
      if (myChart) {
        myChart.setOption({
          xAxis: {
            data: currentChartData.value.xAxisData
          },
          series: currentChartData.value.seriesData
        })
      }
    })
  })
</script>

<style scoped>
  .echarts-bar-container {
    width: 100%;
    height: 100%;
    padding: 0 13px;
    padding-top: 13px;
    display: flex;
    flex-direction: column;
  }
  .top-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .title-area {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .icon {
    margin-right: 6px;
    width: 5px;
    height: 15px;
    background: linear-gradient(90deg, #3d7fff 0%, #81b4ff 100%);
    border-radius: 0px 0px 0px 0px;
    opacity: 0.56;
  }
  .chart-title {
    font-weight: 600;
    font-family: 'Alibaba PuHuiTi 2', 'Alibaba PuHuiTi 2.0';
    font-weight: normal;
    font-size: 16px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    color: #22262f;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }
  .dropdown-area {
    align-self: flex-end;
    margin-bottom: 10px;
  }
  .echarts-box {
    width: 100%;
    height: 100%;
    margin-bottom: 10px;
  }
  :deep(.el-select__wrapper) {
    width: 67px;
    height: 28px;
    padding: 4px !important;
    background: linear-gradient(90deg, #158dff 0%, #4caaff 100%);
    font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
    font-weight: normal;
    font-size: 14px;
    color: #ffffff !important;
    text-align: left;
    font-style: normal;
    text-transform: none;
    border-radius: 6px !important;
    box-shadow: none;
  }
  :deep(.el-select__placeholder) {
    color: #ffffff !important;
    padding-left: 6px;
  }
  :deep(.el-select__caret) {
    color: #ffffff !important;
    padding-right: 4px;
  }
</style>
